package com.besall.allbase.view.activity.chipstoollevel4.customerdial;

import static com.bes.bessdk.BesSdkConstants.BES_CONNECT_ERROR;
import static com.bes.bessdk.BesSdkConstants.BES_CONNECT_SUCCESS;
import static com.bes.bessdk.service.BesOTAConstants.BES_KEY_USE_INTERNAL_FILE_ACCESS;
import static com.bes.bessdk.service.BesOTAConstants.BES_KEY_USE_INTERNAL_FILE_ACCESS_CHOOSE_FILE;
import static com.bes.bessdk.service.customerdial.CustomerDialConstants.CUSTOMER_DIAL_CHOOSE_DIAL_KEY;
import static com.bes.bessdk.service.customerdial.CustomerDialConstants.CUSTOMER_DIAL_GET_FLASH_ADDRESS_RESULT_FAIL;
import static com.bes.bessdk.service.customerdial.CustomerDialConstants.CUSTOMER_DIAL_LOG_INFO;
import static com.bes.bessdk.service.customerdial.CustomerDialConstants.CUSTOM_DIAL_COLORS;
import static com.bes.bessdk.service.customerdial.CustomerDialConstants.OP_TOTA_WRITE_FLASH_PROCESS;
import static com.bes.bessdk.service.customerdial.CustomerDialConstants.OP_TOTA_WRITE_FLASH_WHOLE_CHECK_RESULT_FAIL;
import static com.bes.bessdk.service.customerdial.CustomerDialConstants.OP_TOTA_WRITE_FLASH_WHOLE_CHECK_RESULT_OK;
import static com.bes.bessdk.service.customerdial.CustomerDialConstants.REQUEST_CODE_CHOOSE_DIAL;
import static com.besall.allbase.bluetooth.BluetoothConstants.Scan.BES_SCAN_RESULT;

import static com.besall.allbase.common.Constants.OTA_CHOOSE_FILE_PATH_RESULT;

import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.opengl.ETC1;
import android.opengl.ETC1Util;
import android.os.Build;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.bes.bessdk.BesSdkConstants;
import com.bes.bessdk.scan.BtHeleper;
import com.bes.bessdk.service.base.BesServiceConfig;
import com.bes.bessdk.service.base.BesServiceListener;
import com.bes.bessdk.utils.ArrayUtil;
import com.bes.bessdk.utils.SPHelper;
import com.bes.sdk.device.HmDevice;
import com.bes.sdk.utils.DeviceProtocol;
import bb.lanxing.R;
import com.besall.allbase.bluetooth.BluetoothConstants;
import com.besall.allbase.common.Constants;
import com.besall.allbase.common.utils.ActivityUtils;
import com.besall.allbase.common.utils.FileUtils;
import com.besall.allbase.view.activity.chipstoollevel4.customerdial.makedial.MakeDialActivity;
import com.besall.allbase.view.base.BaseActivity;
import com.suke.widget.SwitchButton;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.HashMap;
import java.util.Map;

/**
 * @author ericshen
 * @time $ $
 */
public class CustomerDialActivity extends BaseActivity<ICustomerDialActivity, CustomerDialPresenter> implements ICustomerDialActivity, BesServiceListener, View.OnClickListener, RadioGroup.OnCheckedChangeListener, SwitchButton.OnCheckedChangeListener {
    private static CustomerDialActivity instance;

    BluetoothDevice mDevice;
    HmDevice mHmDevice;
    BesServiceConfig mServiceConfig;
    CustomerDialBean curDialBean;
    String curDfuFilePath = "";
    String curOldFilePath = "";

    Button choose_dial;
    ImageView show_dial_photo;
    RadioGroup radio_group_file_type;

    SwitchButton switchButton_use_diff_upgrade;
    TextView show_old_file_path;
    TextView show_dial_dfu_path;
    Button choose_old_file;
    Button choose_dfu_file;
    Button choose_device;
    Button start_transfer;
    TextView current_device;
    TextView transfer_percent;
    ProgressBar transfer_progress;

    int curFileType = 1;
    int curRadioGroupCheck = 1;

    byte[] index8BinData = new byte[0];
    boolean clickStart = false;


    @Override
    protected CustomerDialPresenter createPresenter() {
        return new CustomerDialPresenter();
    }

    @Override
    protected void initBeforeSetContent() {
        SPHelper.putPreference(instance, BesSdkConstants.BES_SAVE_LOG_NAME, "CustomerDial OTA");

        mServiceConfig = new BesServiceConfig();
        mServiceConfig.setServiceUUID(BesSdkConstants.BES_SPP_CONNECT);
        boolean useTotaV2 = (boolean) SPHelper.getPreference(instance, BesSdkConstants.BES_TOTA_USE_TOTAV2, BesSdkConstants.BES_TOTA_USE_TOTAV2_VALUE);
        mServiceConfig.setUseTotaV2(useTotaV2);
        mServiceConfig.setTotaConnect(true);
        mServiceConfig.setDeviceProtocol(DeviceProtocol.PROTOCOL_SPP);
    }

    @Override
    protected int getContentViewId() {
        return R.layout.activity_customerdial;
    }

    @Override
    protected void bindView() {
        done = (Button) findViewById(R.id.done);
        loginfo = (View) findViewById(R.id.loginfo);

        switchButton_use_diff_upgrade = (SwitchButton) findViewById(R.id.switchButton_use_diff_upgrade);
        choose_dial = (Button) findViewById(R.id.choose_dial);
        show_dial_photo = (ImageView) findViewById(R.id.show_dial_photo);
        radio_group_file_type = (RadioGroup) findViewById(R.id.radio_group_file_type);
        show_dial_dfu_path = (TextView) findViewById(R.id.show_dial_dfu_path);
        show_old_file_path = (TextView) findViewById(R.id.show_old_file_path);
        choose_dfu_file = (Button) findViewById(R.id.choose_dfu_file);
        choose_old_file = (Button) findViewById(R.id.choose_old_file);
        current_device = (TextView) findViewById(R.id.current_device);
        choose_device = (Button) findViewById(R.id.choose_device);
        start_transfer = (Button) findViewById(R.id.start_transfer);
        transfer_percent = (TextView) findViewById(R.id.transfer_percent);
        transfer_progress = (ProgressBar) findViewById(R.id.transfer_progress);
    }

    @Override
    protected void initView() {
        String titleStr = "CUSTOMER DIAL";
        tv_title.setText(titleStr);
        mToolbar.setTitle("");
        setSupportActionBar(mToolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setHomeButtonEnabled(true);
        done.setOnClickListener(instance);
        tv_title.setOnClickListener(instance);

        switchButton_use_diff_upgrade.setOnCheckedChangeListener(instance);
        choose_dial.setOnClickListener(instance);
        choose_dfu_file.setOnClickListener(instance);
        choose_old_file.setOnClickListener(instance);
        choose_device.setOnClickListener(instance);
        start_transfer.setOnClickListener(instance);
        radio_group_file_type.check(R.id.radio_button_file_type_online);
        radio_group_file_type.setOnCheckedChangeListener(instance);

        refreshUI(false);


    }

    @Override
    protected void setInstance() {
        instance = this;
    }

    @Override
    protected void removeInstance() {
        instance = null;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
//        mPresenter.disconnect();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) {
            return;
        }
        if (requestCode == BluetoothConstants.Scan.REQUEST_CODE_SCAN) {
            onPickDevice(resultCode, data);
        } else if (requestCode == REQUEST_CODE_CHOOSE_DIAL) {
            curDialBean = (CustomerDialBean) data.getSerializableExtra(CUSTOMER_DIAL_CHOOSE_DIAL_KEY);
            Bitmap bitmap = BitmapFactory.decodeFile(curDialBean.getPath());
            show_dial_photo.setVisibility(View.VISIBLE);
            show_dial_photo.setImageBitmap(bitmap);
            start_transfer.setEnabled(true);
            start_transfer.setBackground(getDrawable(R.drawable.ota_button_bg));
            curFileType = 2;
            refreshUI(true);

            clickStart = false;
            index8BinData = new byte[0];
            new Thread(new Runnable() {
                @Override
                public void run() {
                    index8BinData = getIndex8(curDialBean.getPath());
                    String path = "/storage/emulated/0//Android/data/com.bes.watch.dail/files/INDEX_8_BIN_FOLDER/index8.bin";
                    File file = new File(path);
                    if (file.exists()){
                        file.delete();
                    }
                    FileUtils.writeTOFile(index8BinData, "INDEX_8_BIN_FOLDER", "index8", "bin");
                    if (clickStart) {
                        startTransfer(index8BinData);
                    }
                }
            }).start();
        } else if (requestCode == Constants.OTA_CHOOSE_FILE_PATH_RESULT - 1) {
            curDfuFilePath = data.getStringExtra(BES_KEY_USE_INTERNAL_FILE_ACCESS_CHOOSE_FILE);
            Log.i(TAG, "onActivityResult: -------" + curDfuFilePath);
            show_dial_dfu_path.setText(curDfuFilePath);
            start_transfer.setEnabled(true);
            start_transfer.setBackground(getDrawable(R.drawable.ota_button_bg));
            curFileType = curRadioGroupCheck;
            refreshUI(true);
        } else if (requestCode == Constants.OTA_CHOOSE_FILE_PATH_RESULT - 2) {
            curOldFilePath = data.getStringExtra(BES_KEY_USE_INTERNAL_FILE_ACCESS_CHOOSE_FILE);
            show_old_file_path.setText("old file:" + curOldFilePath);
        }
    }

    private void onPickDevice(int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            mHmDevice = (HmDevice) data.getSerializableExtra(BluetoothConstants.Scan.BES_SCAN_RESULT);
            mDevice = BtHeleper.getBluetoothAdapter(instance).getRemoteDevice(mHmDevice.getPreferredProtocol() == DeviceProtocol.PROTOCOL_BLE ? mHmDevice.getBleAddress() : mHmDevice.getDeviceMAC());
            current_device.setText(mDevice.getName() + "   " + mDevice.getAddress());
            current_device.setTextColor(getColor(R.color.btnDisableColor));
            choose_device.setText(getString(R.string.loading));
            mServiceConfig.setDevice(mHmDevice);
            mPresenter.connectDevice(mServiceConfig, instance, instance);
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        if(item.getItemId() == android.R.id.home){
            mPresenter.disconnect();
            finish();
        }

/*        switch (item.getItemId()) {
            case android.R.id.home:
                mPresenter.disconnect();
                finish();
                break;
        }*/
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onClick(View v) {
    	
    	
        if(v.getId() == R.id.choose_device){
            mPresenter.pickDecice(instance, BluetoothConstants.Scan.SCAN_SPP);
     }else if(v.getId() == R.id.choose_dial){
         if (current_device.getCurrentTextColor() != getColor(R.color.green)) {
             showToast(getString(R.string.pleaseCheckTheConnection));
             return;
         }
         ActivityUtils.gotoActForResult(new Intent(), REQUEST_CODE_CHOOSE_DIAL, instance, MakeDialActivity.class);
     }else if(v.getId() == R.id.choose_old_file){
         SPHelper.putPreference(instance, BES_KEY_USE_INTERNAL_FILE_ACCESS, true);
         FileUtils.fileToHex(instance, Constants.OTA_CHOOSE_FILE_PATH_RESULT - 2);
     }else if(v.getId() == R.id.choose_dfu_file){
         SPHelper.putPreference(instance, BES_KEY_USE_INTERNAL_FILE_ACCESS, true);
         FileUtils.fileToHex(instance, Constants.OTA_CHOOSE_FILE_PATH_RESULT - 1);
     }else if(v.getId() == R.id.start_transfer){
    	 LOG(TAG, "click start_transfer");
         if (current_device.getCurrentTextColor() != getColor(R.color.green)) {
             showToast(getString(R.string.pleaseCheckTheConnection));
             return;
         }
         byte[] data = new byte[0];
         if (curFileType == 2) {
             if (curDialBean == null) {
                 showToast(getString(R.string.pleaseSelectOTAFile));
                 return;
             }
             if (index8BinData.length == 0) {
                 clickStart = true;
                 start_transfer.setEnabled(false);
                 start_transfer.setText(getString(R.string.upgradeUnderWay));
                 return;
             }
             data = index8BinData;

         } else {
             if (curDfuFilePath.length() == 0 || (curDfuFilePath.length() > 0 && !(new File(curDfuFilePath).exists()))) {
                 showToast(getString(R.string.pleaseSelectOTAFile));
                 return;
             }
             data = changePathToData(curDfuFilePath);
         }
         if (data == null || data.length == 0) {
             showToast(getString(R.string.pleaseSelectOTAFile));
             return;
         }
         //弃用
//         byte[] oldData = null;
//         if (switchButton_use_diff_upgrade.isChecked()) {
//             if (curOldFilePath.length() == 0) {
//                 showToast(getString(R.string.pleaseSelectOTAFile));
//                 return;
//             }
//             oldData = changePathToData(curOldFilePath);
//             if (oldData.length == 0) {
//                 showToast(getString(R.string.pleaseSelectOTAFile));
//                 return;
//             }
//         }
         startTransfer(data);
      }else if(v.getId() == R.id.done){
          loginfo.setVisibility(View.GONE);
      }else if(v.getId() == R.id.tv_title){
          loginfo.setVisibility(View.VISIBLE);
      }
    	
        /*switch (v.getId()) {
            case R.id.choose_device:
                mPresenter.pickDecice(instance, BluetoothConstants.Scan.SCAN_SPP);
//                changePhotoToPixelData();
                break;
            case R.id.choose_dial:
                if (current_device.getCurrentTextColor() != getColor(R.color.green)) {
                    showToast(getString(R.string.pleaseCheckTheConnection));
                    return;
                }
                ActivityUtils.gotoActForResult(new Intent(), REQUEST_CODE_CHOOSE_DIAL, instance, MakeDialActivity.class);
                break;
            case R.id.choose_old_file:
                SPHelper.putPreference(instance, BES_KEY_USE_INTERNAL_FILE_ACCESS, true);
                FileUtils.fileToHex(instance, Constants.OTA_CHOOSE_FILE_PATH_RESULT - 2);
                break;
            case R.id.choose_dfu_file:
                SPHelper.putPreference(instance, BES_KEY_USE_INTERNAL_FILE_ACCESS, true);
                FileUtils.fileToHex(instance, Constants.OTA_CHOOSE_FILE_PATH_RESULT - 1);
                break;
            case R.id.start_transfer:
                LOG(TAG, "click start_transfer");
                if (current_device.getCurrentTextColor() != getColor(R.color.green)) {
                    showToast(getString(R.string.pleaseCheckTheConnection));
                    return;
                }
                byte[] data = new byte[0];
                if (curFileType == 2) {
                    if (curDialBean == null) {
                        showToast(getString(R.string.pleaseSelectOTAFile));
                        return;
                    }
                    if (index8BinData.length == 0) {
                        clickStart = true;
                        start_transfer.setEnabled(false);
                        start_transfer.setText(getString(R.string.upgradeUnderWay));
                        return;
                    }
                    data = index8BinData;

                } else {
                    if (curDfuFilePath.length() == 0 || (curDfuFilePath.length() > 0 && !(new File(curDfuFilePath).exists()))) {
                        showToast(getString(R.string.pleaseSelectOTAFile));
                        return;
                    }
                    data = changePathToData(curDfuFilePath);
                }
                if (data == null || data.length == 0) {
                    showToast(getString(R.string.pleaseSelectOTAFile));
                    return;
                }
                //弃用
//                byte[] oldData = null;
//                if (switchButton_use_diff_upgrade.isChecked()) {
//                    if (curOldFilePath.length() == 0) {
//                        showToast(getString(R.string.pleaseSelectOTAFile));
//                        return;
//                    }
//                    oldData = changePathToData(curOldFilePath);
//                    if (oldData.length == 0) {
//                        showToast(getString(R.string.pleaseSelectOTAFile));
//                        return;
//                    }
//                }
                startTransfer(data);
                break;
            case R.id.done:
                loginfo.setVisibility(View.GONE);
                break;
            case R.id.tv_title:
                loginfo.setVisibility(View.VISIBLE);
            default:
                break;
        }*/
    }

    private void startTransfer(byte[] data) {
        clickStart = false;
        LOG(TAG, "curOldFilePath:--------" + curOldFilePath);
        LOG(TAG, "curDfuFilePath:--------" + curDfuFilePath);
        start_transfer.setEnabled(false);
        start_transfer.setText(getString(R.string.upgradeUnderWay));
        byte[] param = new byte[0];
        if (curFileType == 2) {
            byte[] type = ArrayUtil.intToBytesLittle(curDialBean.getStyle());
            byte[] color = ArrayUtil.toBytes(CUSTOM_DIAL_COLORS[curDialBean.getColor() < 0 ? 0 : curDialBean.getColor()].replace("#", ""));
            param = new byte[]{type[0], type[1], color[3], color[2], color[1], color[0]};
        }
        mPresenter.startTransfer(null, data, curFileType, switchButton_use_diff_upgrade.isChecked() ? 1 : 0, param);
    }

    @Override
    public void onTotaConnectState(boolean state, HmDevice hmDevice) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (state == true) {
                    choose_device.setText(getString(R.string.change_device_tota_spp));
                    current_device.setTextColor(getColor(R.color.green));
                    showToast(R.string.connect_success);
                } else {
                    choose_device.setText(getString(R.string.change_device_tota_spp));
                    current_device.setTextColor(Color.RED);
                    showToast(R.string.connect_failed);
                }
            }
        });
    }

    @Override
    public void onErrorMessage(int msg, HmDevice hmDevice) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                current_device.setTextColor(Color.RED);
                showToast(R.string.connect_failed);
            }
        });
    }

    @Override
    public void onStateChangedMessage(int msg, String msgStr, HmDevice hmDevice) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (msg == BES_CONNECT_SUCCESS) {

                } else if (msg == BES_CONNECT_ERROR) {
                    choose_device.setText(getString(R.string.change_device_ble));
                    current_device.setTextColor(Color.RED);
                    showToast(R.string.connect_failed);
                } else if (msg == OP_TOTA_WRITE_FLASH_PROCESS) {
                    transfer_percent.setText(msgStr + "%");
                    transfer_progress.setProgress(Float.valueOf(msgStr).intValue());
                } else if (msg == OP_TOTA_WRITE_FLASH_WHOLE_CHECK_RESULT_OK) {
                    showToast(R.string.OTASuccess);
                    start_transfer.setEnabled(false);
                    start_transfer.setBackground(getDrawable(R.drawable.ota_button_bg_press));
                    start_transfer.setText(getString(R.string.start_transfer_tips));
                } else if (msg == OP_TOTA_WRITE_FLASH_WHOLE_CHECK_RESULT_FAIL) {
                    showToast(R.string.OTAFail);
                } else if (msg == CUSTOMER_DIAL_LOG_INFO) {
                    String str = logV.getText() + "\n" + msgStr;
                    logV.setText(str);
                } else if (msg == CUSTOMER_DIAL_GET_FLASH_ADDRESS_RESULT_FAIL) {
                    showToast(R.string.flash_address_error);
                }
            }
        });
    }

    @Override
    public void onSuccessMessage(int msg, HmDevice hmDevice) {

    }

    protected void showToast(int msg) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }

    protected void showToast(String msg) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }



    private byte[] changePathToData(String path) {
        FileInputStream inputStream = null;
        try {
            inputStream = new FileInputStream(path);
            int totalSize = inputStream.available();
            byte[] data = new byte[totalSize];
            inputStream.read(data, 0, totalSize);
            inputStream.close();

            return data;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new byte[0];
    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        curDfuFilePath = "";
        show_dial_dfu_path.setText(curDfuFilePath);
        
        
        if(checkedId == R.id.radio_button_file_type_online){
            curFileType = 1;
            refreshUI(false);
     }else if(checkedId == R.id.radio_button_file_type_picture){
         curFileType = 3;
         refreshUI(false);
     }else if(checkedId == R.id.radio_button_file_type_font){
         curFileType = 4;
         refreshUI(false);
     }else if(checkedId == R.id.radio_button_file_type_tp){
         curFileType = 5;
         refreshUI(false);
     }else if(checkedId == R.id.radio_button_file_type_heart_rate){
         curFileType = 6;
         refreshUI(false);
      }else if(checkedId == R.id.radio_button_file_type_language){
          curFileType = 7;
          refreshUI(false);
      }
        
        
/*        switch (checkedId) {
            case R.id.radio_button_file_type_online:
                curFileType = 1;
                refreshUI(false);
                break;
            case R.id.radio_button_file_type_picture:
                curFileType = 3;
                refreshUI(false);
                break;
            case R.id.radio_button_file_type_font:
                curFileType = 4;
                refreshUI(false);
                break;
            case R.id.radio_button_file_type_tp:
                curFileType = 5;
                refreshUI(false);
                break;
            case R.id.radio_button_file_type_heart_rate:
                curFileType = 6;
                refreshUI(false);
                break;
            case R.id.radio_button_file_type_language:
                curFileType = 7;
                refreshUI(false);
                break;
            default:
                break;
        }*/

        curRadioGroupCheck = curFileType;
    }

    private void refreshUI(boolean isStartBtn) {
        int type = curFileType;
        if (type != 2) {
            show_dial_photo.setVisibility(View.GONE);
            curDialBean = null;
        } else {
            show_dial_dfu_path.setText("");
        }
        String text = "";
        if (type == 1) {
            text = getString(R.string.choose_online_dial);
        }  else if (type == 2) {
            text = getString(R.string.customer_dial);
            switchButton_use_diff_upgrade.setChecked(false);
        } else if (type == 3) {
            text = getString(R.string.choose_picture);
        } else if (type == 4) {
            text = getString(R.string.choose_font_library);
        } else if (type == 5) {
            text = getString(R.string.choose_tp_firmware);
        } else if (type == 6) {
            text = getString(R.string.choose_heart_rate_firmware);
        } else if (type == 7) {
            text = getString(R.string.choose_language_packet);
        }
        if (isStartBtn) {
            start_transfer.setText(getString(R.string.start_ota) + " " + text);
        } else {
            choose_dfu_file.setText(getString(R.string.choose) + " " + text);
        }
    }

    @Override
    public void onCheckedChanged(SwitchButton view, boolean isChecked) {
//        if (isChecked) {
//            show_old_file_path.setVisibility(View.VISIBLE);
//            choose_old_file.setVisibility(View.VISIBLE);
//            curFileType = curRadioGroupCheck;
//            refreshUI(false);
//        } else {
//            show_old_file_path.setVisibility(View.GONE);
//            choose_old_file.setVisibility(View.GONE);
//            curOldFilePath = "";
//            show_old_file_path.setText("");
//        }


    }

    public void LOG(String TAG, String msg) {
//        if (instance == null) {
//            return;
//        }
//        String saveLogName = (String) SPHelper.getPreference(instance, BesSdkConstants.BES_SAVE_LOG_NAME, "");
//        boolean saveLog = (boolean) SPHelper.getPreference(instance, BesSdkConstants.BES_SAVE_LOG_KEY, BesSdkConstants.BES_SAVE_LOG_VALUE);
//        if (saveLog) {
//            if (saveLogName.equals(BES_SAVE_LOG_OTA)) {
//                LogUtils.writeForOTA(TAG, msg, saveLogName);
//            } else if (saveLogName.length() > 0){
//                LogUtils.writeForLOG(TAG, msg, saveLogName);
//            }
//        }
    }

    public byte[] getIndex8(String str) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        String path = str;
        Log.i(TAG, "getIndex8: path---" + path);

        options.inPreferredConfig = Bitmap.Config.ARGB_8888;
        Bitmap bitmap = BitmapFactory.decodeFile(path, options);
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();
        int colorTableSize = 256 * 4;

        byte[] header = new byte[16];
        String headerStr = "IDX8IDX8";
        byte[] header1 = ArrayUtil.toBytes(ArrayUtil.str2HexStr(headerStr));
        byte[] header2 = ArrayUtil.bytesSplic(ArrayUtil.intToBytes2(width), ArrayUtil.intToBytes2(height), ArrayUtil.intToBytes2(colorTableSize), ArrayUtil.intToBytes2(0));
        header = ArrayUtil.byteMerger(header1, header2);
        byte[] indexTab = new byte[width * height];
        byte[] colorTab = new byte[colorTableSize];
        byte[] data = new byte[header.length + indexTab.length + colorTab.length];
        Log.i(TAG, "getIndex8: path---000000");

        Map<String, Integer> colorMap = new HashMap<>();
        for (int i = 0; i < height; i ++) {
            for (int j = 0; j < width; j++) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                    if (bitmap.getColor(j, i).isSrgb()) {
                        Color color = bitmap.getColor(j, i);
                        float A = 255.0f * color.alpha();
                        int intR = (int) (color.red() * A);
                        int intG = (int) (color.green() * A);
                        int intB = (int) (color.blue() * A);
                        int intA = (int) A;
                        String key = intR + "," + intG + "," + intB + "," + intA;


                        if (colorMap.size() < 256 && !colorMap.containsKey(key)) {
                            colorMap.put(key, Integer.valueOf(colorMap.size()));
                        }
                        if (colorMap.size() == 256) {
                            break;
                        }
                    }
                } else {
                    showToast("Android Version Require Android 10 at least");
                    return null;
                }
            }
        }
        Log.i(TAG, "getIndex8: -----" + colorMap.size());

        for (int i = 0; i < height; i ++) {
            for (int j = 0; j < width; j ++) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                    if (bitmap.getColor(j, i).isSrgb()) {
                        Color color = bitmap.getColor(j, i);
                        float A = 255.0f * color.alpha();
                        int intR = (int) (color.red() * A);
                        int intG = (int) (color.green() * A);
                        int intB = (int) (color.blue() * A);
                        int intA = (int) A;
                        String key = intR + "," + intG + "," + intB + "," + intA;
                        indexTab[i * width + j] = (byte) colorMap.get(key).intValue();
                    }
                }
            }
        }
        Log.i(TAG, "getIndex8: path---111111");

        for (String key : colorMap.keySet()) {
            int index = colorMap.get(key).intValue();
            String[] colorArr = key.split(",");
//            Log.i(TAG, "getIndex8: -----" + index);
//            Log.i(TAG, "colorArr: --------" + colorArr[0] + "---" + colorArr[1] + "---" + colorArr[2] + "---" + colorArr[3]);
            byte[] colorByte = new byte[]{(byte) Integer.valueOf(colorArr[0]).intValue(), (byte) Integer.valueOf(colorArr[1]).intValue(), (byte) Integer.valueOf(colorArr[2]).intValue(), (byte) Integer.valueOf(colorArr[3]).intValue()};
//            Log.i(TAG, "colorByte: --------" + colorByte[0] + "---" + colorByte[1] + "---" + colorByte[2] + "---" + colorByte[3]);
            colorTab[index * 4] = colorByte[0];
            colorTab[index * 4 + 1] = colorByte[1];
            colorTab[index * 4 + 2] = colorByte[2];
            colorTab[index * 4 + 3] = colorByte[3];
        }

        System.arraycopy(header, 0, data, 0, header.length);
        System.arraycopy(indexTab, 0, data, header.length, indexTab.length);
        System.arraycopy(colorTab, 0, data, header.length + indexTab.length, colorTab.length);

        return data;
    }
}
